package br.com.foxline.atlasmobile.request;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Message;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import br.com.foxline.atlasmobile.adapter.ListCheckAdapter;
import br.com.foxline.atlasmobile.dao.AnnexDao;
import br.com.foxline.atlasmobile.dao.ImovelDao;
import br.com.foxline.atlasmobile.entities.Annex;
import br.com.foxline.atlasmobile.entities.Imovel;
import br.com.foxline.atlasmobile.entities.Proprietario;
import br.com.foxline.atlasmobile.util.UtilConnection;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class RequestWebJSON extends AsyncTask<List<Imovel>, String, String> {

	private List<Imovel> data;
	private String value;
	private Context context;
	private ProgressDialog dialog;
	private SharedPreferences prefs;
	private String server;
	private String portNumber;
	private ImovelDao imovelDao;
	private AnnexDao annexDao;

	private int cont;
	private int contAnnex;
	private Gson gson;
	private List<Annex> list;
	private List<Annex> listEnviar;
	private ListCheckAdapter adapter;
	private String erros = "";

	public RequestWebJSON(Context context, ListCheckAdapter adapter) {
		super();
		this.context = context;
		this.imovelDao = new ImovelDao(context);
		this.annexDao = new AnnexDao(context);

		this.dialog = new ProgressDialog(context);
		this.dialog.setTitle("Enviando");
		this.dialog.setMessage("Conectando...");
		this.dialog.setCancelable(false);

		this.dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Fechar",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						closeDialog();
					}
				});

		this.dialog.show();

		prefs = this.context.getSharedPreferences(
				UtilConnection.APP_SHARED_PREFS, 0);
		server = prefs.getString(UtilConnection.SERVER,
				UtilConnection.SERVER_DEFAULT);
		portNumber = prefs.getString(UtilConnection.PORT_NUMBER,
				UtilConnection.PORT_NUMBER_DEFAULT);

		this.adapter = adapter;
	}

	public String ImovelJson(Imovel imovel) {

		list = new ArrayList<Annex>();
		listEnviar = new ArrayList<Annex>();

		imovel.setCroquiImovel(null);
		imovel.setCroquiTerreno(null);

		for (Proprietario p : imovel.getProprietarios()) {
			p.setImovel(null);
		}

		for (Annex annex : imovel.getAnnex()) {
			SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
			annex.setCod("#" + annex.getId() + "#" + annex.getUUID() + "#"
					+ sdf.format(annex.getCreate_at()));

			annex.setId(null);
			annex.setImovel(null);
			annex.setContent(null);
			

			list.add(annex);
		}

		// for (Annex a : list) {
		// Annex a1 = new Annex();
		// a1.setCod(a.getCod());
		// a1.setContent(a.getContent());
		// a.setContent(null);
		//
		// listEnviar.add(a1);
		// }

		imovel.setAnnex(list);

		return gson.toJson(imovel);

	}

	@Override
	protected void onProgressUpdate(String... values) {
		super.onProgressUpdate(values);
		if (values.length > 0 && values[0] != null) {
			dialog.setMessage(values[0] + "" + erros);
		}

	}

	@Override
	protected String doInBackground(List<Imovel>... params) {
		data = params[0];

		SynchronousHttpConnection httpConnection = new SynchronousHttpConnection(
				server, portNumber);

		String response;
		gson = new GsonBuilder().setDateFormat("dd/MM/yyyy").create();

		for (Imovel i : data) {
			try {

				
				cont++;
				contAnnex = 0;
				
				response = httpConnection.post(UtilConnection.URL_ASYNC,
						ImovelJson(i));
				
				i = imovelDao.find(i.getId());
				
				i.setEnviado(true);
				i.setDateenviado(new Date());
				
				if (!response.equals("200")) {
					i.setDateenviado(null);
					i.setEnviado(false);
					erros += "\nERRO NO SERVIDOR #" + i.getId();
					publishProgress("ERRO NO SERVIDOR ");
					throw new Exception();
				}

				for (Annex a : i.getAnnex()) {
					
					SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
					
					Annex a1 = new Annex();
					
					String cod = "#" + a.getId() + "#" + a.getUUID() + "#"+ sdf.format(a.getCreate_at());
					a1.setCod(cod);
					
					a1.setContent(a.getContent());
					
					System.err.println("CÓDIGO:"+cod);

					String responseanexo = "";
					contAnnex++;
					
					publishProgress("Enviando Anexo " + contAnnex + " de "+  i.getAnnex().size());
					
					responseanexo = httpConnection.post(UtilConnection.URL_ASYNC, gson.toJson(a1));
					
					if (!response.equals("200")) {
						erros += "\nERRO AO ENVIAR ANEXO [SERVIDOR] #"+ i.getId();
						publishProgress("ERRO NO SERVIDOR ");
					}
				}

				publishProgress("Enviando " + cont + "/" + data.size());
				Thread.sleep(100);
				
			} catch (Exception e) {
				e.printStackTrace();
				i.setEnviado(false);
				erros += "\nERRO AO ENVIAR #" + i.getId();
				publishProgress("ERRO AO ENVIAR");
			}

			this.imovelDao.update(i);
		}

		return "";
	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		value = result;
		dialog.setMessage("Concluído ! \n" + erros);

		System.err.println("Finalizou");
	}

	private void closeDialog() {

		dialog.dismiss();
		adapter.notifyDataSetChanged();
	}
}
